package kafka220;

import ali_kafka.JavaKafkaConfigurer;
import org.apache.kafka.clients.producer.KafkaProducer;
import org.apache.kafka.clients.producer.ProducerConfig;
import org.apache.kafka.clients.producer.ProducerRecord;
import org.apache.kafka.clients.producer.RecordMetadata;

import java.util.Properties;
import java.util.concurrent.Future;

public class ProducerDemo {
    public static void main(String[] args) {
        send();
    }

    public static void send() {
        //设置 sasl 文件的路径
        JavaKafkaConfigurer.configureSasl();
//加载 kafka.properties
        Properties kafkaProperties = JavaKafkaConfigurer.getKafkaProperties();
        Properties props = new Properties();
        props.put(ProducerConfig.BOOTSTRAP_SERVERS_CONFIG, "192.168.1.4:9092");

//Kafka 消息的序列化方式
        props.put(ProducerConfig.KEY_SERIALIZER_CLASS_CONFIG, "org.apache.kafka.common.serialization.StringSerializer");
        props.put(ProducerConfig.VALUE_SERIALIZER_CLASS_CONFIG, "org.apache.kafka.common.serialization.StringSerializer");
//请求的最长等待时间
        props.put(ProducerConfig.MAX_BLOCK_MS_CONFIG, 30 * 1000);
//构造 Producer 对象，注意，该对象是线程安全的，一般来说，一个进程内一个 Producer 对象即可；
//如果想提高性能，可以多构造几个对象，但不要太多，最好不要超过 5 个
        KafkaProducer<String, String> producer = new KafkaProducer<String, String>(props);
//构造一个 Kafka 消息
        String topic = "test01"; //消息所属的 Topic，请在控制台申请之后，填写在这里
        String value = "test msg from jsgx.telis"; //消息的内容
        try {
            ProducerRecord<String, String> producerRecord = new ProducerRecord<String, String>(topic, value);
//            Headers headers = producerRecord.headers();
//            headers.add("head-key","head-value".getBytes());
            System.out.println("producerRecord.toString() = " + producerRecord.toString());
            //发送消息，并获得一个 Future 对象
            Future<RecordMetadata> metadataFuture = producer.send(producerRecord);
            System.out.println("send success");
            //同步获得 Future 对象的结果
            RecordMetadata recordMetadata = metadataFuture.get();
            System.out.println(String.format("recordMetadata =  Produce ok: topic:%s partition:%d offset:%d value:%s",
                    recordMetadata.topic(), recordMetadata.partition(), recordMetadata.offset(), value));
        } catch (Exception e) {
            System.out.println("error occurred");
            e.printStackTrace();
        }
    }
}
